import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:install_apk_plugin/install_apk_plugin.dart';

class HomeViewModel extends BaseViewModel{
  HomeViewModel(BuildContext context) : super(context);

  var url = "https://jz.yytong.com/ccrc/interfaces/serviceApp.do?m=getVersion";
  
  Future<void> getDownloadUrl() async {
    var map = {
      "type":"2"
    };
    showLoadingDialog();
    try{
      var data = await HttpGo.instance.postData(url,data: {"json":jsonEncode(map)}) ;
      hideDialog();
      if("100"==data['status'].toString()){
        var apkUrl = data['url'];
        downloadApk(apkUrl);
      }else{
        showToast(data['message']);
      }
    }catch(e){
      hideDialog();
    }
  }

  Future<void> downloadApk(String apkUrl) async {
    var appDocDir = await getExternalStorageDirectory();
    var path = (appDocDir?.path??"")+"/service.apk";
    AppDownloadUtils().showDownloadDialog(context, apkUrl, path, (path){
      InstallApkPlugin.installApk(path);
    }, (error){
      showToast("下载失败");
    });
  }
}